/*
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.spice.servlet.inject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.spice.servlet.core.components.ComponentFactory;
import org.spice.servlet.core.components.Fields;
import org.spice.servlet.core.components.Resource;
import org.spice.servlet.dispatcher.handler.SpiceSingleton;

public class InjectionStrategy implements FieldInject {

	private 
	List<ComponentFactory> components;

	public 
	InjectionStrategy(List<ComponentFactory> components) {
		this.components = components;
	}
	
	private 
	Map<String, Object> getClassInstance() {
		final Map<String, Object> classInstance = new HashMap<String, Object>();
		final SpiceSingleton bean = SpiceSingleton.getInstance();
		for(ComponentFactory components : this.components){
			if(components.instance() != null){
				classInstance.put(components.getComponentClass().getName(), components.instance());
				bean.setClassInstance(components.getComponentClass().getName(), components.instance());
			}
		}
		return classInstance;
	}

	@Override
	public 
	void inject(final Resource resource) throws Exception {
		for(final ComponentFactory component : this.components){
			if(!component.isInterface()){
				final Map<String, Object> classInstance = getClassInstance();
				final Map<String, String> interfaceInstance = resource.getInterfaceNames();
				final List<Fields> fields = component.getFieldDetails();
				for(final Fields field : fields){
					if(field.isEligibleForWiring()){
						field.getField().setAccessible(true);
						field.getField().set(classInstance.get(component.getComponentClass().getName()), 
								classInstance.get(interfaceInstance.get(field.getField().getType().getName())));
					} 
				}
			}
		}
	}





}
